const { Op } = require("sequelize");
const Shop = require("../model/Shop");
const crypto = require("crypto");
// 添加商户
exports.addShop = async function (userObj) {
	const ins = await Shop.create({
		id: crypto.randomUUID(),
		createBy: userObj.createBy,
		name: userObj.name,
		address: userObj.address,
		phone: userObj.phone,
		type: +userObj.type,
	});
	console.log(ins.toJSON(), "添加成功");
	return ins.toJSON();
};
// 删除商户
exports.deleteShop = async function (id) {
	const res = await Shop.destroy({
		where: {
			id: id,
		},
	});
	console.log(res, "删除成功");
	if (!res) {
		throw "商户不存在";
	}
};
// 修改商户
exports.updateShop = async function (id, userObj) {
	const res = await Shop.update(
		{
			name: userObj.name,
			address: userObj.address,
			phone: userObj.phone,
		},
		{
			where: {
				id: id,
			},
		}
	);
	if(!res[0]) {
		throw "商户不存在";
	}
};
// 修改状态
exports.updateShopState = async function (id, userState) {
	await Shop.update(
		{
			userState: userState,
		},
		{
			where: {
				id: id,
			},
		}
	);
};
// 查询用户所属商户
exports.getShop = async function (id, page = 1, limit = 10, keyword = "") {
	
	const where = {
		createBy: {
			[Op.eq]: id,
		},
	};
	if (keyword) {
		where.name = {
			[Op.like]: `%${keyword}%`,
		};
	}
	const res = await Shop.findAndCountAll({
		where,
		offset: (page - 1) * limit,
		limit: +limit,
	});
	console.log(res);
	return {
		total: res.count,
		data: JSON.parse(JSON.stringify(res.rows)),
	};
};

// 查询商户详情
exports.getShopDetail = async function (id) {
	const res = await Shop.findOne({
		where: {
			id: id,
		},
	});
	if (!res) {
		throw "商户不存在";
	}
	return res.toJSON();
};
